﻿
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Traceability.App.Api.Application.Command.Basic;
using Traceability.App.Api.Controllers;
using Traceability.App.Api.DTOs;
using Traceability.App.ErrorCount;
using Traceability.App.InfrasIntructure;
using Traceability.App.Model;
using Traceability.App.Model.Basic;
using Traceability.App.Model.Cultivation;
using Traceability.App.Model.DeepProcessing;
using Traceability.App.Model.Slaughter;

namespace Traceability.App.Api.Application.Handler.Basic
{
    public class GetBasicHandler : IRequestHandler<GetBasicCommand, ApiPaging<BasicDTO>>
    {
        IBaseRepository<BasicModel> basicRepo;
        IBaseRepository<StoreModel> storeRepo;
        IBaseRepository<CultivationModel> culRepo;
        IBaseRepository<SlaughterModel> slaRepo;
        IBaseRepository<DeepProcessingModel> deepRepo;

        public GetBasicHandler(IBaseRepository<BasicModel> basicRepo, IBaseRepository<StoreModel> storeRepo, IBaseRepository<CultivationModel> culRepo, IBaseRepository<SlaughterModel> slaRepo, IBaseRepository<DeepProcessingModel> deepRepo)
        {
            this.basicRepo = basicRepo;
            this.storeRepo = storeRepo;
            this.culRepo = culRepo;
            this.slaRepo = slaRepo;
            this.deepRepo = deepRepo;
        }

        public async Task<ApiPaging<BasicDTO>> Handle(GetBasicCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<BasicDTO> res = new ApiPaging<BasicDTO>();
            var basics = basicRepo.GetAll().Where(c => !c.IsDeleted);
            var stores = storeRepo.GetAll().Where(c => !c.IsDeleted);
            var breedings = culRepo.GetAll().Where(c => !c.IsDeleted);
            var Slaughter = slaRepo.GetAll().Where(c => !c.IsDeleted);
            var Processing=deepRepo.GetAll().Where(c => !c.IsDeleted);
            if (!string.IsNullOrEmpty(request.StoreName))
            {
                stores = stores.Where(c => c.StoreName.Contains(request.StoreName));
            }
            if (!string.IsNullOrEmpty(request.Batch))
            {
                basics = basics.Where(c => c.Batch.Contains(request.Batch));
            }
            if (request.Expiration != null)
            {
                basics = basics.Where(c => c.Expiration == request.Expiration);
            }
            if (!string.IsNullOrEmpty(request.License))
            {
                basics = basics.Where(c => c.License.Contains(request.License));
            }
            if (!string.IsNullOrEmpty(request.Company))
            {
                basics = basics.Where(c => c.Company.Contains(request.Company));
            }
            if (!string.IsNullOrEmpty(request.Creator))
            {
                basics = basics.Where(c => c.Creator.Contains(request.Creator));
            }
            if (!string.IsNullOrEmpty(request.Updator))
            {
                basics = basics.Where(c => c.Updator.Contains(request.Updator));
            }
            if (request.CreatorDate.HasValue) // 检查查询条件是否有值
            {
                DateTime requestDate = request.CreatorDate.Value.Date; // 获取查询日期（忽略时间）
                basics = basics.Where(c =>
                    c.CreatorDate.HasValue // 确保实体属性有值
                    && c.CreatorDate.Value.Date == requestDate // 比较日期部分
                );
            }
            if (request.UpdatorDate.HasValue) // 检查查询条件是否有值
            {
                DateTime requestDate = request.UpdatorDate.Value.Date; // 获取查询日期（忽略时间）
                basics = basics.Where(c =>
                    c.UpdatorDate.HasValue // 确保实体属性有值
                    && c.UpdatorDate.Value.Date == requestDate // 比较日期部分
                );
            }
            var linq = (from a in basics
                       join b in stores on a.Sid equals b.Id
                        let hasBreeding = breedings.Any(b => b.Batch == a.Batch)
                        let hasSlaughter = Slaughter.Any(s => s.Batch == a.Batch)
                        let hasProcessing = Processing.Any(p => p.Batch == a.Batch)
                        select new BasicDTO
                       {
                           Id = a.Id,
                           Sid = b.Id,
                           Batch = a.Batch,
                           Expiration = a.Expiration,
                           License = a.License,
                           Company = a.Company,
                           Picture = a.Picture,
                           Completeness = CalculateCompleteness(hasBreeding, hasSlaughter, hasProcessing),
                           Creator = a.Creator,
                           CreatorDate = a.CreatorDate,
                           Updator = a.Updator,
                           UpdatorDate = a.UpdatorDate,
                           StoreName = b.StoreName,
                       }).AsQueryable();
            res.TotalCount = linq.Count();
            res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / request.PageSize);
            res.Data = linq.OrderByDescending(c => c.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            foreach (var item in res.Data)
            {
                var basic = await basicRepo.GetAll().FirstOrDefaultAsync(b => b.Batch == item.Batch && !b.IsDeleted);
                if (basic != null)
                {
                    basic.Completeness = item.Completeness;
                    await  basicRepo.Update(basic);
                }


               
            }
            res.Msg = "查询溯源基本信息表成功";
            res.Code = ApiEnum.Success;
            return res;

        }
        private static int CalculateCompleteness(bool hasBreeding, bool hasSlaughter, bool hasProcessing)
        {
            int completeness = 10;
            if (hasBreeding) completeness += 30;
            if (hasSlaughter) completeness += 30;
            if (hasProcessing) completeness += 30;
            return completeness;
        }
    }
}
